package com.spdd.mt.task;

import cn.hutool.core.util.StrUtil;
import com.spdd.mt.biz.config.ConfigBean;
import com.spdd.mt.biz.constant.OrderStatus;
import com.spdd.mt.biz.entity.MtRechargeOrderEntity;
import com.spdd.mt.biz.manager.feishu.FeiShuService;
import com.spdd.mt.biz.manager.service.OrderService;
import com.spdd.mt.biz.service.MtRechargeOrderService;
import com.spdd.mt.common.util.JacksonUtils;
import com.spdd.mt.config.ScheduledCondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单重发任务
 */
@Slf4j
@Component
@Conditional(ScheduledCondition.class)
public class CompensateReorderTask {

    @Autowired
    private ConfigBean configBean;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MtRechargeOrderService rechargeOrderService;

    @Autowired
    private FeiShuService feiShuService;

    /**
     * 每10分钟执行一次
     */
    @Scheduled(cron = "0 */10 * * * ?")
    public void reorder() {
        log.info("开始执行重发订单任务");

        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        // 查询待重发的起始时间
        LocalDateTime beginTime = now.minusHours(configBean.getReorderQueryTime());
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String begin = beginTime.format(timeFormatter);
        String end = now.format(timeFormatter);
        List<MtRechargeOrderEntity> list = new ArrayList<>();
        // 遍历 beginTime 到 now 之间的每一天
        long daysBetween = ChronoUnit.DAYS.between(beginTime.toLocalDate(), now.toLocalDate());
        try {
            for (int i = 0; i <= daysBetween; i++) {
                String date = beginTime.plusDays(i).toLocalDate().format(dateFormatter);
                log.info("开始查询 [{}] 待重发订单的数据, begin={}, end={}", date, begin, end);
                list.addAll(rechargeOrderService.getNeedReOrder(date.substring(0, 6), date, configBean.getMaxReorderTimes(),
                        begin, end, configBean.getReorderQueryCount()));
            }
        } catch (Exception e) {
            feiShuService.sendExceptionMsg(e);
            log.error("执行重发订单任务异常, msg=" + e.getMessage(), e);
            return;
        }

        log.info("待重发订单的数据量:{}", list.size());
        log.info("开始批量重发");
        for (MtRechargeOrderEntity order : list) {
            try {
                if (StrUtil.isBlank(order.getSupplierOrderNo())) {
                    log.info("执行重发操作 order: {}", JacksonUtils.toJson(order));
                    orderService.reorder(order);
                } else {
                    log.info("美团订单号:{} 已经重发，无需再发送，供应商订单号:{}", order.getMtOrderNo(), order.getSupplierOrderNo());
                    log.info("更新重发状态为重发成功");
                    rechargeOrderService.updateReorder(order.getTradeMonth(), order.getId(),
                            OrderStatus.SUCCESS.getValue(), null);
                    // log.info("更新重发状态结果:{}", flag);
                }

            } catch (Exception e) {
                feiShuService.sendExceptionMsg(e);
                log.error("重发订单异常, msg=" + e.getMessage(), e);
            }
        }
        log.info("批量重发完成");
        log.info("执行重发订单任务务结束");
    }
}
